import { go } from '@/assets/js/go';
import { guid, focusInput } from '@/util/helpers';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { addOrUpdateApi, getApiInfo } from '@/api/product/station-manage';
let G = go.GraphObject.make; //GOJS对象
let _designer = {}; //右键菜单对象
let _myContextMenu = {};
export default {
  components: {
    CommonModalTemplate
  },
  inject: ['reload'],
  data() {
    return {
      apiFlowId: '',
      apiInfo: {
        url: '/api/mes-product/apaas/api/command/spec'
      }, //api信息
      paletteData: [], //左侧控件数据
      paletteList: [
        {
          key: guid(),
          text: '检查',
          category: '202010160001',
          imgsrc: '/img/station-flow/check.png',
          nodeType: 'CHECKER',
          nodeTypeName: '检查',
          nodeCode: 'Checker',
          operationalCharacter: 'AND',
          failAction: 'continue',
          checkItemList: []
        },
        {
          key: guid(),
          text: '绑定',
          category: '202010160002',
          imgsrc: '/img/station-flow/meet.png',
          nodeType: 'BINDINGPREPARE',
          nodeTypeName: '绑定',
          nodeCode: 'BindingPrepare',
          bindingType: ''
        },
        {
          key: guid(),
          text: '解绑',
          category: '202010160003',
          imgsrc: '/img/station-flow/unmeet.png',
          nodeType: 'UNBINDINGPREPARE',
          nodeTypeName: '解绑',
          nodeCode: 'UnBindingPrepare',
          unbindingType: ''
        },
        {
          key: guid(),
          text: '打印',
          category: '202010160004',
          imgsrc: '/img/station-flow/listener.png',
          nodeType: 'PRINT',
          nodeTypeName: '打印',
          nodeCode: 'Print',
          mappingApiId: '',
          mappingApiName: ''
        },
        {
          key: guid(),
          text: '过站',
          category: '202010160005',
          imgsrc: '/img/station-flow/update.png',
          nodeType: 'OVERSTATIONPREPARE',
          nodeTypeName: '过站',
          nodeCode: 'OverStationPrepare'
        },
        {
          key: guid(),
          text: '流程卡包装',
          category: '202010160006',
          imgsrc: '/img/station-flow/update.png',
          nodeType: 'PROCESSCARDPACK',
          nodeTypeName: '流程卡包装',
          nodeCode: 'processCardPack'
        }
      ],
      defaultData: [
        {
          key: 'Start',
          text: '开始',
          category: 'Start',
          location: '-50 -340',
          imgsrc: '/img/station-flow/start.png',
          nodeType: 'START',
          nodeTypeName: '开始'
        },
        {
          key: 'End',
          text: '结束',
          category: 'End',
          location: '-50 250',
          imgsrc: '/img/station-flow/end.png',
          nodeType: 'END',
          nodeTypeName: '结束'
        }
      ], //默认开始结束节点数据
      apiType: '', //API类型
      activeName: '1', //API基本信息显示Tabs
      apiInfoRules: {
        name: [
          {
            required: true,
            message: '请输入API响应名称',
            trigger: 'submit',
            validator: (rule, value, callback) => {
              callback();
            }
          }
        ],
        code: [
          {
            required: true,
            message: '请输入API响应编码',
            trigger: 'submit',
            validator: (rule, value, callback) => {
              callback();
            }
          }
        ],
        url: [
          {
            required: true,
            message: '请输入API地址',
            trigger: 'submit',
            validator: (rule, value, callback) => {
              callback();
            }
          }
        ]
      }, //API基本信息表单验证
      paramsData: [], //API基本信息参数信息
      paramsOption: {
        //API基本信息参数信息配置
        height: 300,
        calcHeight: 30,
        border: true,
        index: false,
        selection: true,
        addBtn: false,
        viewBtn: false,
        menu: false,
        tip: false,
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        column: [
          {
            label: '参数',
            prop: 'code'
          },
          {
            label: '注释',
            prop: 'value'
          }
        ]
      },
      paramsSelectionList: [], //API参数列表选中数据
      modalName: '',
      timer: new Date().getTime(),
      tableOption: {}, //公用模态框表格属性
      nodeInfoActiveName: '1', //节点信息Tabs
      selectedNodeInfo: {}, //当前操作的节点信息
      basicInfoRules: {
        text: [
          {
            required: true,
            message: '请输入节点名称',
            trigger: 'submit',
            validator: (rule, value, callback) => {
              callback();
            }
          }
        ],
        nodeCode: [
          {
            required: true,
            message: '请输入节点编码',
            trigger: 'submit',
            validator: (rule, value, callback) => {
              callback();
            }
          }
        ]
      }, //基本信息表单验证
      selectedNodeInfoDefaults: {},
      checkNodeInfoOption: {
        //检查节点信息配置
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '110',
        labelPosition: 'top',
        column: [
          {
            label: '检查组合运算符',
            prop: 'operationalCharacter',
            type: 'select',
            dicData: [
              {
                label: '并且',
                value: 'AND'
              },
              {
                label: '或者',
                value: 'OR'
              }
            ],
            span: 24,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          },
          {
            label: '失败后动作',
            prop: 'failAction',
            type: 'select',
            dicData: [
              {
                label: '继续执行',
                value: 'continue'
              },
              {
                label: '终止流程',
                value: 'stop'
              }
            ],
            span: 24,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          }
        ]
      },
      bindingNodeInfoOption: {
        //绑定节点信息配置
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '110',
        labelPosition: 'top',
        column: [
          {
            label: '绑定类型',
            prop: 'bindingType',
            type: 'select',
            dicData: [
              {
                label: '组装',
                value: 'Assemble'
              },
              {
                label: '离线内包装',
                value: 'InnerPackOff'
              },
              {
                label: '离线外包装',
                value: 'OuterPackOff'
              },
              {
                label: '在线内包装',
                value: 'InnerPackOn'
              },
              {
                label: '在线外包装',
                value: 'OuterPackOn'
              },
              {
                label: '分组',
                value: 'Group'
              },
              {
                label: '绑定老化车',
                value: 'BindAgingCar'
              },
              {
                label: '上料',
                value: 'Feeding'
              },
              {
                label: '载具包装',
                value: 'CarrierPack'
              },
              {
                label: '载具接驳',
                value: 'Tranship'
              },
              {
                label: '载具包装产品',
                value: 'CarrierPackProduct'
              },
              {
                label: '载具绑定产品',
                value: 'CarrierBindingProduct'
              }
            ],
            span: 24,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          }
        ]
      },
      unbindingNodeInfoOption: {
        //解绑节点信息
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '110',
        labelPosition: 'top',
        column: [
          {
            label: '解绑类型',
            prop: 'unbindingType',
            type: 'select',
            dicData: [
              {
                label: '取消分组',
                value: 'cancelGroup'
              },
              {
                label: '解绑工具',
                value: 'UnBindAgingCar'
              },
              {
                label: '拆板',
                value: 'Split'
              }
            ],
            span: 24,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          }
        ]
      },
      overStationNodeInfoOption: {
        //记录数据节点信息配置
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '110',
        labelPosition: 'top',
        column: [
          {
            label: '过站类型',
            prop: 'overStationType',
            type: 'select',
            dicData: [
              {
                label: '过站',
                value: 'OverStation'
              },
              {
                label: '报工',
                value: 'Timesheet'
              },
              {
                label: '进老化',
                value: 'InAging'
              },
              {
                label: '出老化',
                value: 'OutAging'
              },
              {
                label: '包装称重',
                value: 'PackWeighing'
              },
              {
                label: '载具进老化',
                value: 'CarrierInAging'
              },
              {
                label: '载具出老化',
                value: 'CarrierOutAging'
              },
              {
                label: '内包装报工',
                value: 'InnerPackReport'
              },
              {
                label: '测试',
                value: 'Test'
              },
              {
                label: '报工及不良',
                value: 'TimesheetDefect'
              },
              {
                label: '不良绑定',
                value: 'Defect'
              }
              // {
              //   label: '扣料',
              //   value: 'PartDeduct'
              // }
            ],
            span: 24,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          }
        ]
      }
    };
  },

  created() {},

  mounted() {
    this.initToolbar('myPaletteDiv', this.paletteList);
    this.init('myFlowDesignerDiv', this.paletteList);
    if (this.$route.query.apiId) {
      this.apiFlowId = this.$route.query.apiId;
      this.getModelFlowInfo(this.apiFlowId);
    }
  },

  watch: {
    $route: {
      handler() {
        this.reload();
      }
    },
    'selectedNodeInfo.text'() {
      this.formKeyUpFunction();
    },
    'selectedNodeInfo.nodeCode'() {
      this.formKeyUpFunction();
    },
    'this.selectedNodeInfo.operationalCharacter'() {
      this.formKeyUpFunction();
    },
    'selectedNodeInfo.failAction'() {
      this.formKeyUpFunction();
    },
    'selectedNodeInfo.bindingType'() {
      this.formKeyUpFunction();
    },
    'selectedNodeInfo.unbindingType'() {
      this.formKeyUpFunction();
    },
    'selectedNodeInfo.overStationType'() {
      this.formKeyUpFunction();
    },
    'selectedNodeInfo.operationalCharacter'() {
      this.formKeyUpFunction();
    },
    'selectedNodeInfo.failAction'() {
      this.formKeyUpFunction();
    }
  },

  methods: {
    //-----------------------------------------流程设计相关代码----------------------------------------------------
    /**
     * 初始化流程设计器
     * @param divId 设计器Div
     */
    initToolbar(div, myPaletteData) {
      this.paletteData = this.defaultData.concat(myPaletteData);
      let myPalette = G(go.Palette, div, {
        layout: G(go.GridLayout, {
          sorting: go.GridLayout.Forward,
          cellSize: new go.Size(1, 1),
          wrappingColumn: 1,
          isViewportSized: true
        })
      });
      for (var i = 0; i < this.paletteData.length; i++) {
        myPalette.nodeTemplateMap.add(
          this.paletteData[i].category,
          this.makePaletteNodeTemplate(this.paletteData[i].imgsrc || '@/assets/img/order-route/conveyor_blue.png', this.paletteData[i].key)
        );
      }

      myPalette.model.nodeDataArray = this.paletteData;

      myPalette.nodes.each(function (node) {
        node.ports.each(function (port) {
          port.cursor = '';
        });
        node.elements.each(function (tb) {
          if (tb instanceof go.TextBlock) {
            tb.visible = true;
          }
        });
      });
    },

    /**
     * 创建右侧设计框中模板
     * @param {*} imgsrc
     */
    makePaletteNodeTemplate(imgsrc, key) {
      return G(
        go.Node,
        'Horizontal',
        {
          locationSpot: go.Spot.Center
        },
        new go.Binding('location', 'location', go.Point.parse).makeTwoWay(go.Point.stringify),
        {
          selectable: true,
          selectionAdornmentTemplate: this.makeNodeSelectionAdornmentTemplate(),
          doubleClick: (e, node) => {
            let flowData = JSON.parse(this.getFlowData());
            let currentNode = this._cloneDeep(node.part.data);

            //判断是否存在相同节点
            let repeatNode = this._find(flowData.nodeDataArray, { text: currentNode.text });
            if (repeatNode) {
              this.$confirm(`已经存在 ${currentNode.text} 工站，不能重复添加`, '提示', {
                confirmButtonText: '确定',
                type: 'warning'
              });
              return;
            }

            //判断是否存在开始、结束节点
            let startNode = this._find(flowData.nodeDataArray, { text: '开始' });
            let endNode = this._find(flowData.nodeDataArray, { text: '结束' });
            if (!startNode && currentNode.text !== '开始') {
              this.$confirm('请拖拽出开始节点！', '提示', {
                confirmButtonText: '确定',
                type: 'warning'
              });
              return;
            }
            if (!endNode && currentNode.text !== '结束') {
              this.$confirm('请拖拽出结束节点！', '提示', {
                confirmButtonText: '确定',
                type: 'warning'
              });
              return;
            }

            let _length = this._get(flowData, 'nodeDataArray.length', 0);
            currentNode['location'] = this.locationArray[_length - 2];

            if (_length > 0) {
              if (currentNode.text === '开始' || currentNode.text === '结束') {
                _designer.model.addNodeData(currentNode);
              } else {
                let nodeData = this._filter(flowData.nodeDataArray, (item) => {
                  return item.text !== '开始' && item.text !== '结束';
                });
                _designer.model.addNodeData(currentNode);
                if (nodeData.length === 0) {
                  _designer.model.addLinkData({ from: 'Start', to: currentNode.key });
                } else {
                  //当出现nodeData顺序与工序路线顺序不一致的时候会导致连线出现问题
                  _designer.model.addLinkData({ from: nodeData[nodeData.length - 1].key, to: currentNode.key });
                  //删除线条
                  let _node = _designer.findNodeForKey('End');
                  _designer.startTransaction('Deleted Links');
                  _designer.removeParts(_node.findLinksConnected());
                  _designer.commitTransaction('Deleted Links');
                }
                _designer.model.addLinkData({ from: currentNode.key, to: 'End' });
                // debugger
                // let lastNodeLocation = flowData.nodeDataArray[flowData.nodeDataArray.length - 2].location;
                // let xLocation = lastNodeLocation.split(' ')[0];
                // let yLocation = lastNodeLocation.split(' ')[1];
                // console.log(lastNodeLocation);
                // // -650
                // // -510
                // let newXLocation = Number(xLocation) + 140;
                // let newYLocation = Number(yLocation);

                // let newLocation = String(newXLocation) + ' ' + String(newYLocation);
                // currentNode['location'] = newLocation;

                //判断当前设计框中的节点数量，来设定结束节点的位置
                //首先拿到这个节点的data对象
                let nodeInfo = _designer.model.findNodeDataForKey('End');
                if (nodeData.length >= 4) {
                  //然后对这个对象的属性进行更改，如果没有则新增这个属性
                  _designer.model.setDataProperty(nodeInfo, 'location', this.locationArray[10]);
                }

                if (nodeData.length >= 10) {
                  _designer.model.setDataProperty(nodeInfo, 'location', this.locationArray[16]);
                }

                if (nodeData.length >= 16) {
                  _designer.model.setDataProperty(nodeInfo, 'location', this.locationArray[22]);
                }

                if (nodeData.length >= 22) {
                  _designer.model.setDataProperty(nodeInfo, 'location', this.locationArray[28]);
                }

                //用获取页面中对应输入框的方法来获取设计图中有无该工站，若没有则赋值
                if (currentNode.category !== 'Start' && currentNode.category !== 'End') {
                  this.selectedNodeInfo = { ...currentNode };
                  switch (currentNode.nodeType) {
                    case 'CHECKER':
                      this.selectedNodeInfo.operationalCharacter = 'AND';
                      this.selectedNodeInfo.failAction = 'continue';
                      break;

                    default:
                      break;
                  }
                }
              }
              //默认选中新节点
              var nodeKey = _designer.model.findNodeDataForKey(currentNode.key);
              var selectNode = _designer.findNodeForData(nodeKey);
              _designer.select(selectNode);
            }
          }
        },
        G(go.Picture, imgsrc, {
          width: 50,
          height: 50,
          margin: 2,
          portId: '',
          fromLinkable: key == 'End' ? false : true,
          toLinkable: key == 'Start' ? false : true,
          toMaxLinks: 1,
          fromMaxLinks: 1,
          cursor: 'move'
        }),
        G(
          go.TextBlock,
          '默认文本',
          {
            editable: false,
            margin: 0,
            textAlign: 'center',
            width: 90,
            maxLines: 1,
            overflow: go.TextBlock.OverflowEllipsis,
            alignment: go.Spot.Right,
            cursor: 'move'
          },
          new go.Binding('text', 'text')
        ),
        {
          toolTip: this.makeTooltipTemplate()
        }
      );
    },

    /**
     * 选中节点的样式
     * @returns {*}
     */
    makeNodeSelectionAdornmentTemplate() {
      return G(
        go.Adornment,
        'Auto',
        G(go.Shape, {
          fill: null,
          stroke: 'deepskyblue',
          // strokeWidth: 1.6,
          strokeWidth: 2,
          strokeDashArray: [4, 2]
        }),
        G(go.Placeholder)
      );
    },

    /**
     * 悬浮在某一个图标上提示信息/tooltip上显示的信息
     */
    makeTooltipTemplate() {
      return G(
        go.Adornment,
        go.Panel.Auto,
        G(go.Shape, 'RoundedRectangle', {
          fill: 'whitesmoke',
          stroke: 'gray'
        }),
        G(
          go.TextBlock,
          {
            margin: 5,
            editable: true
          },
          new go.Binding('text', '', function (data) {
            if (data.text !== undefined) return data.text;
            return '(未命名)';
          })
        )
      );
    },

    /**
     * 初始化流程设计器
     * @param divId 设计器Div
     */
    init(divId, myPaletteData) {
      this.paletteData = this.defaultData.concat(myPaletteData);
      _designer = G(go.Diagram, divId, {
        //设计框中网格样式
        grid: G(
          go.Panel,
          'Grid',
          G(go.Shape, 'LineH', {
            stroke: 'lightgray',
            strokeWidth: 0.5
          }),
          G(go.Shape, 'LineH', {
            stroke: 'gray',
            strokeWidth: 0.5,
            interval: 10
          }),
          G(go.Shape, 'LineV', {
            stroke: 'lightgray',
            strokeWidth: 0.5
          }),
          G(go.Shape, 'LineV', {
            stroke: 'gray',
            strokeWidth: 0.5,
            interval: 10
          })
        ),
        // "linkingTool.direction": go.LinkingTool.ForwardsOnly,
        initialContentAlignment: go.Spot.Center, //初始位置在中间，若设置则"modelData": {"position":"-5 -5"},
        allowDrop: true, // must be true to accept drops from the Palette
        allowTextEdit: false, //允许文本编辑
        allowHorizontalScroll: true, //允许水平滑动
        allowVerticalScroll: true, //允许垂直滑动
        click: function (e, obj) {},
        'toolManager.mouseWheelBehavior': go.ToolManager.WheelZoom, //允许轮滑滚动
        'draggingTool.dragsLink': false, //线条是否可以拖拽
        'draggingTool.isGridSnapEnabled': true,
        'linkingTool.isUnconnectedLinkValid': false, //是否可以放置不连接的线
        'linkingTool.portGravity': 20,
        'relinkingTool.isUnconnectedLinkValid': false, //拖动之后可以放置不连接的线
        'relinkingTool.portGravity': 20,
        'relinkingTool.fromHandleArchetype': G(go.Shape, 'Diamond', {
          segmentIndex: 0,
          cursor: 'pointer',
          desiredSize: new go.Size(8, 8),
          fill: 'tomato',
          stroke: 'darkred'
        }),
        'relinkingTool.toHandleArchetype': G(go.Shape, 'Diamond', {
          segmentIndex: -1,
          cursor: 'pointer',
          desiredSize: new go.Size(8, 8),
          fill: 'darkred',
          stroke: 'tomato'
        }),
        'linkReshapingTool.handleArchetype': G(go.Shape, 'Diamond', {
          desiredSize: new go.Size(7, 7),
          fill: 'lightblue',
          stroke: 'deepskyblue'
        }),
        'undoManager.isEnabled': true
      });
      //新增分组功能
      _designer.groupTemplate = G(
        go.Group,
        {
          resizable: true,
          resizeObjectName: 'SHAPE'
        },
        new go.Binding('position', 'pos', go.Point.parse).makeTwoWay(go.Point.stringify),
        {},
        G(
          go.Shape,
          'Rectangle', // the rectangular shape around the members
          {
            name: 'SHAPE',
            fill: null,
            stroke: 'deepskyblue'
          },
          new go.Binding('desiredSize', 'size', go.Size.parse).makeTwoWay(go.Size.stringify)
        )
      );

      _designer.commandHandler.memberValidation = function (grp, node) {
        if (grp instanceof go.Group && node instanceof go.Group) return false;
        return true;
      };

      //删除选中工站事件
      _designer.addDiagramListener('SelectionDeleted', (ev) => {
        this.selectedNodeInfo = {};
        // selectedFirstTab('apiInfo');
      });

      //工艺路线上切换选择工站事件
      _designer.addDiagramListener('ChangedSelection', (ev) => {
        this.onChangedSelection();
      });

      //工艺路线上单击事件
      _designer.addDiagramListener('ObjectSingleClicked', (ev) => {
        var part = ev.subject.part;
        //判断当前点击元素是哪一个的实例，执行不同的动作
        if (part instanceof go.Node) {
          this.onObjectSingleClicked(part);
        } else if (part instanceof go.Link) {
          //选中线条时当前对象为空
          this.selectedNodeInfo = {};
          // selectedFirstTab('apiInfo');
        }
      });

      //工艺路线上右击事件
      _designer.addDiagramListener('ObjectContextClicked', (ev) => {
        var part = ev.subject.part;
        //判断当前点击元素是哪一个的实例，执行不同的动作
        if (part instanceof go.Node) {
          this.onObjectSingleClicked(part);
        } else if (part instanceof go.Link) {
          //选中线条时当前对象为空
          this.selectedNodeInfo = {};
          // selectedFirstTab('apiInfo');
        }
      });

      //不在任何部分的单击
      _designer.addDiagramListener('BackgroundSingleClicked', (event) => {
        this.selectedNodeInfo = {};
        // selectedFirstTab('apiInfo');
      });

      //拖放节点到这个图表中时事件
      _designer.addDiagramListener('ExternalObjectsDropped', (event) => {
        event.subject.each((part) => {
          //用获取页面中对应输入框的方法来获取设计图中有无该工站，若没有则赋值
          if (part.data.category !== 'Start' && part.data.category !== 'End') {
            this.selectedNodeInfo = { ...part.data };
            // this.$forceUpdate();
            this.$set(this.selectedNodeInfo, 'nodeType', this.selectedNodeInfo.nodeType);
            // selectedFirstTab('nodeInfo');
          } else {
            this.selectedNodeInfo = {};
            // selectedFirstTab('apiInfo');
          }
        });
        // debugger
        // 停止任何正在进行的文本编辑
        // if (_designer.currentTool instanceof go.TextEditingTool) {
        //     _designer.currentTool.acceptText(go.TextEditingTool.LostFocus);
        // }
        // 展开任何“宏”
        _designer.commandHandler.ungroupSelection();
        // 开始编辑取消组后下降的第一个节点
        // var tb = _designer.selection.first().findObject('TEXT');
        // if (tb) _designer.commandHandler.editTextBlock(tb);
      });

      //一个不在任何部分的上下文单击;
      // _designer.addDiagramListener("BackgroundContextClicked", this.onBackgroundContextClicked);

      // //遍历模板数据生成中间设计框
      for (var i = 0; i < this.paletteData.length; i++) {
        _designer.nodeTemplateMap.add(this.paletteData[i].category, this.makeNodeTemplate(this.paletteData[i].imgsrc || Config.WORKSHOP_DEFAULT_ICON, this.paletteData[i].key));
      }
      // 流程连接线的样式模板
      _designer.linkTemplate = this.makeLinkTemplate();
      //分组样式模版
      // _designer.groupTemplate = groupTemplate();
      _designer.contextMenu = _myContextMenu;
    },

    /**
     * 拖拽出来的工站单击事件，将当前点击的工站信息渲染值右侧表单中
     * @param part
     */
    onObjectSingleClicked(part) {
      if (part.data.category === 'Start' || part.data.category === 'End') {
        layer.msg(this.translate.instant('开始和结束步骤不可编辑'));
        this.$confirm('开始和结束步骤不可编辑', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        this.selectedNodeInfo = {};
        // Helpers.selectedFirstTab('apiInfo');
        return;
      }
      //当两次点击的工站key值相同时则不进行赋值
      if (this.selectedNodeInfo.key === part.data.key) {
        return;
      }
      this.selectedNodeInfo = { ...part.data };
      // Helpers.selectedFirstTab('nodeInfo');
      switch (this.selectedNodeInfo.nodeType) {
        case 'CHECKER':
          this.selectedNodeInfo.operationalCharacter = this._get(this.selectedNodeInfo, 'operationalCharacter', 'AND');
          this.selectedNodeInfo.failAction = this._get(this.selectedNodeInfo, 'failAction', 'continue');
          break;
        case 'OVERSTATIONPREPARE':
          this.selectedNodeInfo.overStationType = this._get(this.selectedNodeInfo, 'overStationType', '');
          // let recordFiledsList = this._get(this.selectedNodeInfo, 'recordFiledsList', []);
          // setTimeout(() => {
          //     this.gridFiledsOptions.api.setRowData(recordFiledsList);
          // }, 80);
          break;
        case 'BINDINGPREPARE':
          this.selectedNodeInfo.bindingType = this._get(this.selectedNodeInfo, 'bindingType', '');
          break;
        case 'UNBINDINGPREPARE':
          this.selectedNodeInfo.unbindingType = this._get(this.selectedNodeInfo, 'unbindingType', '');
        default:
          break;
      }
    },

    /**
     * 创建中间设计框中拖拽模板
     * @param {*} imgsrc
     */
    makeNodeTemplate(imgsrc, key) {
      return G(
        go.Node,
        'Vertical',
        {
          locationSpot: go.Spot.Center
        },
        new go.Binding('location', 'location', go.Point.parse).makeTwoWay(go.Point.stringify),
        {
          selectable: true,
          selectionAdornmentTemplate: this.makeNodeSelectionAdornmentTemplate()
        },
        G(go.Picture, imgsrc, {
          width: 50,
          height: 50,
          margin: 2,
          portId: '',
          fromLinkable: key == 'End' ? false : true,
          toLinkable: key == 'Start' ? false : true,
          toMaxLinks: 1,
          fromMaxLinks: 1,
          cursor: 'pointer'
        }),
        G(
          go.TextBlock,
          '默认文本',
          {
            editable: false,
            margin: 0,
            textAlign: 'center',
            width: 100,
            maxLines: 1,
            overflow: go.TextBlock.OverflowEllipsis,
            alignment: go.Spot.Right,
            cursor: 'move'
          },
          new go.Binding('text', 'text')
        ),
        {
          toolTip: this.makeTooltipTemplate(),
          contextMenu: _myContextMenu
        }
      );
    },

    /**
     * 定义连接线的样式模板
     *
     * @returns {*}
     */
    makeLinkTemplate() {
      return G(
        go.Link, // the whole link panel
        {
          selectable: true,
          selectionAdornmentTemplate: this.makeLinkSelectionAdornmentTemplate()
        },
        {
          relinkableFrom: true,
          relinkableTo: true,
          reshapable: true,
          resegmentable: true
        },
        {
          routing: go.Link.AvoidsNodes,
          curve: go.Link.JumpOver,
          corner: 5,
          toShortLength: 4
        },
        G(
          go.Shape, // 线条
          {
            isPanelMain: true,
            stroke: '#666',
            strokeWidth: 2
          }
        ),
        G(
          go.Shape, // 箭头
          {
            toArrow: 'Standard',
            stroke: '#666'
          }
        ),
        G(
          go.Panel,
          'Auto',
          G(
            go.Shape, // 标签背景色
            {
              fill: null,
              stroke: null
            },
            new go.Binding('fill', 'pFill')
          ),
          G(
            go.TextBlock, // 标签文本
            {
              textAlign: 'center',
              font: '9pt helvetica, arial, sans-serif',
              margin: 4,
              editable: true // enable in-place editing
            },
            // new go.Binding("text", "text"))
            new go.Binding('text').makeTwoWay()
          )
        )
      );
    },

    /**
     * 连接线的选中样式，线条中文本的选中样式
     * @returns {*}
     */
    makeLinkSelectionAdornmentTemplate() {
      return G(
        go.Adornment,
        'Link',
        G(go.Shape, {
          isPanelMain: true,
          fill: null,
          stroke: '#1E90FF',
          strokeWidth: 0
        }),
        G(
          go.TextBlock,
          {
            textAlign: 'center',
            font: '10pt helvetica, arial, sans-serif',
            stroke: 'blue',
            margin: 2
          },
          new go.Binding('text', 'text')
        )
      );
    },

    /**
     * 设计面板中工站切换事件
     * @param ev
     */
    onChangedSelection() {
      let flowData = JSON.parse(this.getFlowData());
      let selectedNode = this._find(flowData.nodeDataArray, { key: this.selectedNodeInfo.key });
      this.selectedNodeInfo = { ...selectedNode };
    },

    /**
     * 获取流程图数据
     * @returns {*}
     */
    getFlowData() {
      _designer.model.modelData.position = go.Point.stringify(_designer.position);
      return _designer.model.toJson();
    },

    apiTypeChange() {
      switch (this.apiType) {
        case '过站工站':
          this.showCrossStationFlow();
          break;
        case '测试工站':
          this.showTestStationFlow();
          break;
        case '组装工站':
          this.showAssemblyStationFlow();
          break;
        case '在线内包装':
          this.showInPackFlow();
          break;
        default:
          break;
      }
    },

    showCrossStationFlow() {
      let data = {
        class: 'go.GraphLinksModel',
        modelData: { position: '-338.4295918367347 -465.2418305896578' },
        nodeDataArray: [
          { key: 'Start', text: '开始', category: 'Start', location: '-50 -420', imgsrc: '/img/station-flow/start.png', nodeType: 'START', nodeTypeName: '开始' },
          {
            key: '3ceb497e-9ea9-43e5-88eb-7d358511c405',
            text: '检查是否为载具扫码',
            category: '202010160001',
            imgsrc: '/img/station-flow/check.png',
            nodeType: 'CHECKER',
            nodeTypeName: '检查',
            nodeCode: 'Checker',
            operationalCharacter: 'AND',
            failAction: 'continue',
            checkItemList: [
              {
                lastModifiedDate: '2021-01-26 09:50:04',
                lastModifiedBy: 1,
                errorMessage: '序列号{SN.oroductSerialNo}不存在！',
                errorCode: '018',
                judgeValueSource: 'fixedValue',
                judgeValue: 'true',
                createdDate: '2021-01-26 09:50:04',
                field: 'SN.isTool',
                createdBy: 1,
                id: 35,
                name: '是否是载具编号扫码',
                operationalCharacter: '==',
                status: 'ACTIVE'
              }
            ],
            location: '-50 -320',
            sequence: 0
          },
          {
            key: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e3',
            text: '检查序列号状态',
            category: '202010160001',
            imgsrc: '/img/station-flow/check.png',
            nodeType: 'CHECKER',
            nodeTypeName: '检查',
            nodeCode: 'SN.status',
            operationalCharacter: 'AND',
            failAction: 'continue',
            checkItemList: [
              {
                judgeValue: 'true',
                createdDate: '2020-10-19 15:53:02',
                field: 'SN.isLocked',
                createdBy: 1660,
                lastModifiedDate: '2020-10-19 15:53:02',
                lastModifiedBy: 1660,
                errorMessage: '产品序列号{SN.productSerialNo}已经被锁定，请先解锁！',
                errorCode: 'error',
                id: 5,
                name: '产品序列号是否被锁定',
                operationalCharacter: '!=',
                status: 'ACTIVE'
              },
              {
                judgeValue: 'true',
                createdDate: '2020-10-20 09:48:36',
                field: 'SN.isRepairHold',
                createdBy: 1660,
                lastModifiedDate: '2020-10-20 09:48:36',
                lastModifiedBy: 1660,
                errorMessage: '产品序列号在{SN.repairingStationName}进入不良管理',
                errorCode: 'error',
                id: 6,
                zhCnName: '产品序列号是否在不良维修管理',
                operationalCharacter: '!=',
                status: 'ACTIVE'
              },
              {
                lastModifiedDate: '2020-12-02 10:34:56',
                lastModifiedBy: 80,
                errorMessage: '产品序列号当前所在工站为：{SN.currentStationName}',
                errorCode: 'error1',
                judgeValueSource: 'dataBase',
                judgeValue: 'currentStationId',
                createdDate: '2020-12-02 10:34:56',
                field: 'SN.currentWorkOrderRouteStationId',
                createdBy: 80,
                id: 10,
                zhCnName: '产品序列号的区域是否正确',
                operationalCharacter: '==',
                status: 'ACTIVE'
              }
            ],
            location: '-50 -220',
            sequence: 1
          },
          {
            key: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e32',
            text: '检查序列号料品',
            category: '202010160001',
            imgsrc: '/img/station-flow/check.png',
            nodeType: 'CHECKER',
            nodeTypeName: '检查',
            nodeCode: 'SN.partNo',
            operationalCharacter: 'AND',
            failAction: 'continue',
            checkItemList: [
              {
                lastModifiedDate: '2020-11-02 15:57:12',
                lastModifiedBy: 1660,
                errorMessage: '产品序列号料号{SN.partNo}与工单上产品料号{WO.partNo}一致，请检查后再次扫描！',
                errorCode: 'error',
                judgeValueSource: 'dataBase',
                judgeValue: 'WO.partNo',
                createdDate: '2020-11-02 15:57:12',
                field: 'SN.WO.partNo',
                createdBy: 1660,
                id: 7,
                name: '产品序列号料号与工单上产品料号是否一致',
                operationalCharacter: '==',
                status: 'ACTIVE'
              }
            ],
            location: '-50 -100',
            sequence: 2
          },
          {
            key: 'bd9d0950-0471-4bff-a15d-06497fadbf23',
            text: '过站',
            category: '202010160005',
            imgsrc: '/img/station-flow/record.png',
            nodeType: 'OVERSTATIONPREPARE',
            nodeTypeName: '过站',
            nodeCode: 'OverStationPrepare',
            recordFiledsList: [],
            location: '-50 50',
            sequence: 3,
            overStationType: 'OverStation'
          },
          { key: 'End', text: '结束', category: 'End', location: '-50 170', imgsrc: '/img/station-flow/end.png', nodeType: 'END', nodeTypeName: '结束' }
        ],
        linkDataArray: [
          { from: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e3', to: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e32' },
          { from: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e32', to: 'bd9d0950-0471-4bff-a15d-06497fadbf23' },
          { from: 'bd9d0950-0471-4bff-a15d-06497fadbf23', to: 'End' },
          { from: 'Start', to: '3ceb497e-9ea9-43e5-88eb-7d358511c405' },
          { from: '3ceb497e-9ea9-43e5-88eb-7d358511c405', to: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e3' }
        ]
      };
      this.displayFlow(JSON.stringify(data));
    },

    showTestStationFlow() {
      let data = {
        class: 'go.GraphLinksModel',
        modelData: { position: '-560 -451.7439208984375' },
        nodeDataArray: [
          { key: 'Start', text: '开始', category: 'Start', location: '-50 -360', imgsrc: '/img/station-flow/start.png', nodeType: 'START', nodeTypeName: '开始' },
          {
            key: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e3',
            text: '检查序列号状态',
            category: '202010160001',
            imgsrc: '/img/station-flow/check.png',
            nodeType: 'CHECKER',
            nodeTypeName: '检查',
            nodeCode: 'SN.status',
            operationalCharacter: 'AND',
            successAction: '继续执行',
            checkItemList: [
              {
                judgeValue: 'true',
                createdDate: '2020-10-19 15:53:02',
                field: 'SN.isLocked',
                createdBy: 1660,
                lastModifiedDate: '2020-10-19 15:53:02',
                lastModifiedBy: 1660,
                errorMessage: '产品序列号{SN.productSerialNo}已经被锁定，请先解锁！',
                errorCode: 'error',
                id: 5,
                name: '产品序列号是否被锁定',
                operationalCharacter: '!=',
                status: 'ACTIVE'
              },
              {
                lastModifiedDate: '2020-11-02 15:57:16',
                lastModifiedBy: 1660,
                errorMessage: '产品序列号在{SN.repairingStationName}进入不良管理',
                errorCode: 'error',
                judgeValueSource: 'fixedValue',
                judgeValue: 'true',
                createdDate: '2020-11-02 15:57:16',
                field: 'SN.isRepairHold',
                createdBy: 1660,
                id: 6,
                zhCnName: '产品序列号是否在不良维修管理',
                operationalCharacter: '!=',
                status: 'ACTIVE'
              }
            ],
            location: '-50 -240',
            sequence: 0
          },
          {
            key: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e32',
            text: '检查序列号料品',
            category: '202010160001',
            imgsrc: '/img/station-flow/check.png',
            nodeType: 'CHECKER',
            nodeTypeName: '检查',
            nodeCode: 'SN.partNo',
            operationalCharacter: 'AND',
            successAction: '继续执行',
            checkItemList: [
              {
                lastModifiedDate: '2020-11-02 15:57:12',
                lastModifiedBy: 1660,
                errorMessage: '产品序列号料号{SN.partNo}与工单上产品料号{WO.partNo}一致，请检查后再次扫描！',
                errorCode: 'error',
                judgeValueSource: 'dataBase',
                judgeValue: 'WO.partNo',
                createdDate: '2020-11-02 15:57:12',
                field: 'SN.WO.partNo',
                createdBy: 1660,
                id: 7,
                name: '产品序列号料号与工单上产品料号是否一致',
                operationalCharacter: '==',
                status: 'ACTIVE'
              }
            ],
            location: '-50 -150',
            sequence: 1
          },
          {
            key: '88060398-f2d6-47bd-9131-5e0d79477762',
            text: '检查',
            category: '202010160001',
            imgsrc: '/img/station-flow/check.png',
            nodeType: 'CHECKER',
            nodeTypeName: '检查',
            nodeCode: 'Checker',
            operationalCharacter: 'AND',
            successAction: '继续执行',
            checkItemList: [
              {
                lastModifiedDate: '2020-11-24 11:08:03',
                lastModifiedBy: 1660,
                errorMessage: '产品序列号当前所在工站为：{SN.currentStationName}',
                errorCode: 'error1',
                judgeValueSource: 'dataBase',
                judgeValue: 'currentStationId',
                createdDate: '2020-11-24 11:08:03',
                field: 'SN.currentWorkOrderRouteStationId',
                createdBy: 1660,
                id: 10,
                name: '产品序列号的区域是否正确',
                operationalCharacter: '==',
                status: 'ACTIVE'
              }
            ],
            location: '-50 -60',
            sequence: 2
          },
          {
            key: '286f0254-df13-4086-812a-c1839df6f653',
            text: '过站',
            category: '202010160005',
            imgsrc: '/img/station-flow/record.png',
            nodeType: 'OVERSTATIONPREPARE',
            nodeTypeName: '过站',
            nodeCode: 'record',
            recordFiledsList: [],
            location: '-50 20',
            sequence: 3,
            recordType: 'OverStation'
          },
          { key: 'End', text: '结束', category: 'End', location: '-50 180', imgsrc: '/img/station-flow/end.png', nodeType: 'END', nodeTypeName: '结束' }
        ],
        linkDataArray: [
          { from: 'Start', to: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e3' },
          { from: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e3', to: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e32' },
          { from: 'aa3c8d86-233c-4a66-bf11-08b88cbb60e32', to: '88060398-f2d6-47bd-9131-5e0d79477762' },
          { from: '88060398-f2d6-47bd-9131-5e0d79477762', to: '286f0254-df13-4086-812a-c1839df6f653' },
          { from: '286f0254-df13-4086-812a-c1839df6f653', to: 'End' }
        ]
      };
      this.displayFlow(JSON.stringify(data));
    },

    showAssemblyStationFlow() {
      let data = {
        class: 'go.GraphLinksModel',
        modelData: { position: '-635 -304.5' },
        nodeDataArray: [
          { key: 'Start', text: '开始', category: 'Start', location: '-580 0', imgsrc: '/img/station-flow/start.png', nodeType: 'START', nodeTypeName: '开始' },
          {
            key: 'e4a1ee57-dc56-4c1e-9826-cacb01d4b578',
            text: '检查子件序列号',
            category: '202010160001',
            imgsrc: '/img/station-flow/check.png',
            nodeType: 'CHECKER',
            nodeTypeName: '检查',
            nodeCode: 'Checker',
            operationalCharacter: 'AND',
            successAction: '继续执行',
            checkItemList: [
              {
                lastModifiedDate: '2020-12-01 08:54:39',
                lastModifiedBy: 80,
                errorMessage: '关键序列号还未完成生产！',
                errorCode: '123',
                judgeValueSource: 'fixedValue',
                judgeValue: 'true',
                createdDate: '2020-12-01 08:54:39',
                field: 'KSN.isCompleted',
                createdBy: 80,
                id: 19,
                name: '关键序列号是否完成',
                operationalCharacter: '==',
                status: 'ACTIVE'
              },
              {
                lastModifiedDate: '2020-11-26 16:33:51',
                lastModifiedBy: 80,
                errorMessage: '子件序列号产品编码不属于关键料品中',
                errorCode: '001',
                judgeValueSource: 'dataBase',
                judgeValue: 'KSN.WO.partNo',
                createdDate: '2020-11-26 16:33:51',
                field: 'SN.workOrderRouteStationParts.partNo',
                createdBy: 80,
                id: 21,
                zhCnName: '检查子件序列号产品编码是否属于关键料品中',
                operationalCharacter: '==',
                status: 'ACTIVE'
              }
            ],
            location: '-500 10',
            sequence: 0,
            failAction: 'continue'
          },
          {
            key: '716a9bce-20b5-47ed-83f8-54fe8861b95e',
            text: '子件序列号是否被组装',
            category: '202010160001',
            imgsrc: '/img/station-flow/check.png',
            nodeType: 'CHECKER',
            nodeTypeName: '检查',
            nodeCode: 'Checker',
            operationalCharacter: 'AND',
            successAction: '继续执行',
            checkItemList: [
              {
                lastModifiedDate: '2020-11-27 09:50:05',
                lastModifiedBy: 80,
                errorMessage: '关键序列号已被组装',
                errorCode: '0002',
                judgeValueSource: 'fixedValue',
                judgeValue: 'true',
                createdDate: '2020-11-27 09:50:05',
                field: 'KSN.isAssembled',
                createdBy: 80,
                id: 22,
                name: '关键序列号是否被组装',
                operationalCharacter: '!=',
                status: 'ACTIVE'
              },
              {
                lastModifiedDate: '2020-11-27 10:31:54',
                lastModifiedBy: 80,
                errorMessage: '关键物料已组装完成',
                errorCode: '003',
                judgeValueSource: 'fixedValue',
                judgeValue: 'true',
                createdDate: '2020-11-27 10:31:54',
                field: 'KSN.isInstalled',
                createdBy: 80,
                id: 23,
                zhCnName: '关键物料是否已组装完成',
                operationalCharacter: '!=',
                status: 'ACTIVE'
              }
            ],
            location: '-350 0',
            sequence: 1,
            failAction: 'continue'
          },
          {
            key: '4fe02522-1a10-452c-aa9f-f1d011be78112',
            text: '检查是否组装完成',
            category: '202010160001',
            imgsrc: '/img/station-flow/check.png',
            nodeType: 'CHECKER',
            nodeTypeName: '检查',
            nodeCode: 'Checker',
            operationalCharacter: 'AND',
            successAction: '继续执行',
            checkItemList: [
              {
                lastModifiedDate: '2020-11-26 14:34:46',
                lastModifiedBy: 80,
                errorMessage: '序列号已组装完成！',
                errorCode: '001',
                judgeValueSource: 'dataBase',
                judgeValue: 'SN.stationPartsLenth',
                createdDate: '2020-11-26 14:34:46',
                field: 'SN.workOrderRouteStationParts.requestQtyTotal',
                createdBy: 80,
                id: 20,
                name: '检查产品序列号是否组装完成',
                operationalCharacter: '!=',
                status: 'ACTIVE'
              }
            ],
            location: '-250 10',
            sequence: 2
          },
          {
            key: 'd09a9fe3-5d7d-489e-9ebf-ce34d229ba16',
            text: '组装',
            category: '202010160002',
            imgsrc: '/img/station-flow/meet.png',
            nodeType: 'BINDINGPREPARE',
            nodeTypeName: '绑定',
            nodeCode: 'BindingPrepare',
            bindingType: 'Assemble',
            location: '-120 0',
            sequence: 3
          },
          {
            key: 'd3042784-e804-469e-a213-6eb23247d8c4',
            text: '过站',
            category: '202010160005',
            imgsrc: '/img/station-flow/record.png',
            nodeType: 'OVERSTATIONPREPARE',
            nodeTypeName: '过站',
            nodeCode: 'overStationPrepare',
            recordFiledsList: [],
            location: '-20 -10',
            sequence: 4,
            recordType: 'OverStation'
          },
          { key: 'End', text: '结束', category: 'End', location: '240 0', imgsrc: '/img/station-flow/end.png', nodeType: 'END', nodeTypeName: '结束' }
        ],
        linkDataArray: [
          { from: 'Start', to: 'e4a1ee57-dc56-4c1e-9826-cacb01d4b578' },
          { from: '4fe02522-1a10-452c-aa9f-f1d011be78112', to: 'd09a9fe3-5d7d-489e-9ebf-ce34d229ba16' },
          { from: '716a9bce-20b5-47ed-83f8-54fe8861b95e', to: '4fe02522-1a10-452c-aa9f-f1d011be78112' },
          { from: 'e4a1ee57-dc56-4c1e-9826-cacb01d4b578', to: '716a9bce-20b5-47ed-83f8-54fe8861b95e' },
          { from: 'd09a9fe3-5d7d-489e-9ebf-ce34d229ba16', to: 'd3042784-e804-469e-a213-6eb23247d8c4' },
          { from: 'd3042784-e804-469e-a213-6eb23247d8c4', to: 'End' }
        ]
      };
      this.displayFlow(JSON.stringify(data));
    },

    showInPackFlow() {
      let data = {
        class: 'go.GraphLinksModel',
        modelData: { position: '-823 -300.2560791015625' },
        nodeDataArray: [
          { key: 'Start', text: '开始', category: 'Start', location: '-170 -260', imgsrc: '/img/station-flow/start.png', nodeType: 'START', nodeTypeName: '开始' },
          {
            key: '162c1d33-0ebd-440d-b9eb-e1e560c9686d',
            text: '绑定',
            category: '202010160002',
            imgsrc: '/img/station-flow/meet.png',
            nodeType: 'BINDINGPREPARE',
            nodeTypeName: '绑定',
            nodeCode: 'BindingPrepare',
            bindingType: 'InnerPackOn',
            location: '-170 -140',
            sequence: 0
          },
          {
            key: '66e17a85-a6ab-4509-8bf3-94805bbae1f9',
            text: '过站',
            category: '202010160005',
            imgsrc: '/img/station-flow/record.png',
            nodeType: 'OVERSTATIONPREPARE',
            nodeTypeName: '过站',
            nodeCode: 'overStationPrepare',
            recordFiledsList: [],
            location: '-170 -30',
            sequence: 1,
            recordType: 'OverStation'
          },
          {
            key: '0784693b-dc12-4293-96c2-93661a1bce56',
            text: '打印',
            category: '202010160004',
            imgsrc: '/img/station-flow/listener.png',
            nodeType: 'PRINT',
            nodeTypeName: '打印',
            nodeCode: 'print',
            mappingApiId: 1000000065,
            mappingApiName: '通过包装条码查询包装信息',
            location: '-180 90',
            sequence: 2
          },
          { key: 'End', text: '结束', category: 'End', location: '-210 350', imgsrc: '/img/station-flow/end.png', nodeType: 'END', nodeTypeName: '结束' }
        ],
        linkDataArray: [
          { from: 'Start', to: '162c1d33-0ebd-440d-b9eb-e1e560c9686d' },
          { from: '162c1d33-0ebd-440d-b9eb-e1e560c9686d', to: '66e17a85-a6ab-4509-8bf3-94805bbae1f9' },
          { from: '66e17a85-a6ab-4509-8bf3-94805bbae1f9', to: '0784693b-dc12-4293-96c2-93661a1bce56' },
          { from: '0784693b-dc12-4293-96c2-93661a1bce56', to: 'End' }
        ]
      };
      this.displayFlow(JSON.stringify(data));
    },

    /**
     * 在设计面板中显示流程图
     * @param flowData  流程图json数据
     */
    displayFlow(flowData) {
      if (!flowData) return;

      _designer.model = go.Model.fromJson(flowData);

      var pos = _designer.model.modelData.position;
      if (pos) _designer.initialPosition = go.Point.parse(pos);
      this.selectedNodeInfo = {};
      // Helpers.selectedFirstTab('apiInfo');
    },

    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },

    /**
     * 新增API基本信息参数
     */
    addParams() {
      this.modalName = 'paramsModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择常用参数（请点击复选框进行多选）',
        url: '/api/blade-system/dict/dictionary?code=STATION_CENTER_PARAMS_LIST',
        isPage: false,
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '参数',
            prop: 'dictKey',
            search: true
          },
          {
            label: '注释',
            prop: 'dictValue',
            search: true
          },
          {
            label: '序号',
            prop: 'sort'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },

    /**
     * 参数信息选择
     */
    paramsSelectionChange(list) {
      this.paramsSelectionList = list;
    },

    /**
     * 删除API基本信息参数
     */
    deleteParams() {
      for (let i = 0; i < this.paramsSelectionList.length; i++) {
        for (let j = 0; j < this.paramsData.length; j++) {
          if (this.paramsSelectionList[i].code === this.paramsData[j].code) {
            this.paramsData.splice(j, 1);
            break;
          }
        }
      }
    },

    /**
     * 添加检查项
     */
    addCheckItem() {
      this.modalName = 'checkItemModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择常用参数（请点击复选框进行多选）',
        url: '/api/mes-product/apaas/check/item/page',
        isPage: true,
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '检查项名称',
            prop: 'name',
            searchLabelWidth: 100,
            search: true
          },
          {
            label: '检查项字段',
            prop: 'field',
            searchLabelWidth: 100,
            search: true
          },
          {
            label: '检查项运算符',
            prop: 'operationalCharacter'
          },
          {
            label: '判断值',
            prop: 'judgeValue'
          },
          {
            label: '错误编号',
            prop: 'errorCode'
          },
          {
            label: '错误信息',
            prop: 'errorMessage'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },

    /**
     * 移除检查项
     */
    removeCheckItem(index) {
      this.selectedNodeInfo.checkItemList.splice(index, 1);
      var node = _designer.model.findNodeDataForKey(this.selectedNodeInfo.key);
      _designer.model.setDataProperty(node, 'checkItemList', this.selectedNodeInfo.checkItemList);
    },

    /**
     * 模态框表格选中数据返回
     */
    getSelectedRows(data) {
      switch (this.modalName) {
        case 'paramsModal':
          let selectedData = this._map(data, (item) => {
            return {
              code: item.dictKey,
              value: item.dictValue
            };
          });
          let paramMapData = this.paramsData;
          paramMapData.push(...selectedData);

          let hash = {}; //去重
          this.paramsData = paramMapData.reduce((preVal, curVal) => {
            hash[curVal.code] ? '' : (hash[curVal.code] = true && preVal.push(curVal));
            return preVal;
          }, []);
          break;
        case 'checkItemModal':
          let flag = true;
          this._forEach(this.selectedNodeInfo.checkItemList, (owner) => {
            this._forEach(data, (item) => {
              if (item.field === owner.field) {
                this.$message({
                  type: 'warning',
                  message: `${item.name}已存在！`
                });
                flag = false;
                return;
              }
            });
          });

          if (flag) {
            this.selectedNodeInfo.checkItemList = this.selectedNodeInfo.checkItemList.concat(data);
            var node = _designer.model.findNodeDataForKey(this.selectedNodeInfo.key);
            _designer.model.setDataProperty(node, 'checkItemList', this.selectedNodeInfo.checkItemList);
          }
          break;
        default:
          break;
      }
    },

    //----------------------------------------检查节点相关代码开始---------------------------------------
    formKeyUpFunction() {
      console.log(this.selectedNodeInfo.text);
      // 首先拿到这个节点的对象
      var node = _designer.model.findNodeDataForKey(this.selectedNodeInfo.key);
      // 然后对这个对象的属性进行更改
      _designer.model.setDataProperty(node, 'text', this.selectedNodeInfo.text);
      _designer.model.setDataProperty(node, 'nodeCode', this.selectedNodeInfo.nodeCode);

      switch (this.selectedNodeInfo.nodeType) {
        case 'CHECKER':
          _designer.model.setDataProperty(node, 'operationalCharacter', this.selectedNodeInfo.operationalCharacter);
          _designer.model.setDataProperty(node, 'failAction', this.selectedNodeInfo.failAction);
          break;
        case 'BINDINGPREPARE':
          _designer.model.setDataProperty(node, 'bindingType', this.selectedNodeInfo.bindingType);
          break;
        case 'UNBINDINGPREPARE':
          _designer.model.setDataProperty(node, 'unbindingType', this.selectedNodeInfo.unbindingType);
          break;
        case 'OVERSTATIONPREPARE':
          _designer.model.setDataProperty(node, 'overStationType', this.selectedNodeInfo.overStationType);
          break;
        default:
          break;
      }
    },

    /**
     * 重构流程数据
     * @param data
     */
    refactringProcessData(data) {
      let startNode = [];
      let endNode = [];
      let startLength = 0; //开始节点个数
      let endLength = 0; //结束节点个数
      let nodeList = []; //流程顺序节点列表
      let isSmooth = false;

      startNode = this._filter(data.linkDataArray, function (item) {
        return item.from.indexOf('Start') > -1;
      });

      startLength = startNode.length;

      if (startLength === 0) {
        this.$confirm('没有连接开始节点', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return [];
      } else if (startLength > 1) {
        this.$confirm('存在多个连接开始节点', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return [];
      } else if (startNode[0].to === 'End') {
        this.$confirm('连接节点：开始节点不能直接连接结束节点！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return [];
      }

      endNode = this._filter(data.linkDataArray, function (item) {
        return item.to === 'End';
      });

      endLength = endNode.length;

      if (endLength === 0) {
        this.$confirm('没有连接结束节点', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return [];
      } else if (endLength > 1) {
        this.$confirm('存在多个连接结束节点', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return [];
      }

      nodeList = [startNode[0].to];
      isSmooth = this.getNodeList(data.linkDataArray, startNode[0].to, nodeList);
      if (!isSmooth) {
        this.$confirm('获取不到配置连接工站！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return [];
      }

      //当拖拽出来的工站数组的数量减去线条数组的数量不等1时则判定有未连接的线
      if (data.nodeDataArray.length - data.linkDataArray.length !== 1) {
        this.$confirm('连接节点不连续，请重新配置！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return [];
      }

      //获取需要的节点信息
      console.log(nodeList);
      let nodeInfoList = this._map(nodeList, (item, index) => {
        let flowData = JSON.parse(this.getFlowData());
        let nodeDataArray = this._filter(flowData.nodeDataArray, (item) => {
          return item.key !== 'Start' && item.key !== 'End';
        });
        let selectedNode = this._find(nodeDataArray, { key: item });
        selectedNode['sequence'] = index;
        return selectedNode;
      });
      console.log(nodeInfoList);
      return nodeInfoList;
    },

    /**
     * 获取节点顺序
     * @param linkDataArray 连接线数据
     * @param key 开始节点
     * @param nodeList  节点顺序
     * return 是否成功连接
     */
    getNodeList(linkDataArray, key, nodeList) {
      let linkData = this._find(linkDataArray, function (item) {
        return item.from === key;
      });
      if (!linkData) {
        return false;
      }
      if (linkData.to != 'End') {
        nodeList.push(linkData.to);
        this.getNodeList(linkDataArray, linkData.to, nodeList);
      }
      return true;
    },

    /**
     * 保存工站模型流程
     */
    saveStationFlowData() {
      if (!this.apiInfo.name) {
        this.activeName = '1';
        this.$confirm('请输入API响应名称！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          focusInput('name');
        });
        this.selectedNodeInfo = {};
        return;
      }
      if (!this.apiInfo.code) {
        this.activeName = '1';
        this.$confirm('请输入API响应编码！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          focusInput('code');
        });
        this.selectedNodeInfo = {};
        return;
      }
      if (!this.apiInfo.url) {
        this.activeName = '1';
        this.$confirm('请输入API地址！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          focusInput('url');
        });
        this.selectedNodeInfo = {};
        return;
      }

      // debugger
      console.log(this.getFlowData());

      let stationFlowJson = JSON.parse(this.getFlowData());

      //判断重复节点
      let flagArray = new Array();
      let flagRepeat = false;
      let repeatStation = '';
      this._forEach(stationFlowJson.nodeDataArray, (item) => {
        if (flagArray[item.text]) {
          flagRepeat = true;
          repeatStation = item.text;
        }
        flagArray[item.text] = true;
      });
      // if (flagRepeat) {
      //     this.$confirm(`${repeatStation}节点重复，请删除其中一个！`, '提示', {
      //         confirmButtonText: '确定',
      //         type: 'warning'
      //     });
      //     return;
      // }
      let nodeInfoList = this.refactringProcessData(stationFlowJson);
      if (nodeInfoList.length === 0) {
        this.$confirm('获取不到配置连接节点', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }
      //校验
      let nodeItem = this._find(nodeInfoList, (item) => {
        //未配置节点名称
        if (!item.text) {
          return item;
        }
        //未配置节点编码
        if (!item.nodeCode) {
          return item;
        }
        if (item.nodeType === 'CHECKER' && !item.operationalCharacter) {
          return item;
        }
        if (item.nodeType === 'CHECKER' && !item.failAction) {
          return item;
        }
        if (item.nodeType === 'BINDINGPREPARE' && !item.bindingType) {
          return item;
        }
        if (item.nodeType === 'UNBINDINGPREPARE' && !item.unbindingType) {
          return item;
        }
        if (item.nodeType === 'OVERSTATIONPREPARE' && !item.overStationType) {
          return item;
        }
        if (item.nodeType === 'PRINT' && !item.mappingApiId) {
          return item;
        }
      });
      //若存在则有信息未配置完全，则对应提示错误信息
      if (nodeItem) {
        //默认选中新节点
        var nodeKey = _designer.model.findNodeDataForKey(nodeItem.key);
        var selectNode = _designer.findNodeForData(nodeKey);
        _designer.select(selectNode);
        this.selectedNodeInfo = { ...nodeItem };
        if (!nodeItem.text) {
          // this.layerMsg('请输入节点名称！', 'text');
          this.nodeInfoActiveName = '1';
          this.$confirm('请输入节点名称！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            focusInput('text');
          });
          return;
        }
        if (!nodeItem.nodeCode) {
          this.$confirm('请输入节点编码！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            focusInput('nodeCode');
          });
          return;
        }
        if (nodeItem.nodeType === 'CHECKER' && !nodeItem.operationalCharacter) {
          this.$confirm('请选择检查组合运算符！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          });
          return;
        }
        if (nodeItem.nodeType === 'CHECKER' && !nodeItem.failAction) {
          this.$confirm('请选择失败后动作！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          });
          return;
        }
        if (nodeItem.nodeType === 'BINDINGPREPARE' && !nodeItem.bindingType) {
          this.$confirm('请选择绑定类型！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          });
          return;
        }
        if (nodeItem.nodeType === 'UNBINDINGPREPARE' && !nodeItem.unbindingType) {
          this.$confirm('请选择解绑类型！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          });
          return;
        }
        if (nodeItem.nodeType === 'OVERSTATIONPREPARE' && !nodeItem.overStationType) {
          this.$confirm('请选择过站类型！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          });
          return;
        }
        // if (nodeItem.nodeType === 'PRINT' && !nodeItem.mappingApiId) {
        //     this.$confirm('请选择API响应！', '提示', {
        //         confirmButtonText: '确定',
        //         type: 'warning'
        //     });
        //     return;
        // }
      }

      //构造S Language
      let sLanguageList = [];
      this._forEach(nodeInfoList, (item) => {
        if (item.nodeType === 'CHECKER') {
          let CHECKLanguage = ``;
          let checkGroupsDetailItemStr = '';
          this._forEach(item.checkItemList, (checkGroupsDetailItem) => {
            let errorMessageStr = '';
            if (checkGroupsDetailItem.errorMessage) {
              errorMessageStr = `err_msg:${checkGroupsDetailItem.errorMessage},`;
            }
            checkGroupsDetailItemStr += `(src:${checkGroupsDetailItem.field},op:${checkGroupsDetailItem.operationalCharacter},dest_source:${checkGroupsDetailItem.judgeValueSource},dest:${checkGroupsDetailItem.judgeValue},err_code:${checkGroupsDetailItem.errorCode},${errorMessageStr}fail_action:${item.failAction})`;
            checkGroupsDetailItemStr += item.operationalCharacter;
          });
          checkGroupsDetailItemStr = checkGroupsDetailItemStr.slice(0, checkGroupsDetailItemStr.length - item.operationalCharacter.length);
          CHECKLanguage += `{{<type:Checker,name:${item.nodeCode}>{${checkGroupsDetailItemStr}}}}`;
          if (CHECKLanguage) {
            sLanguageList.push(CHECKLanguage);
          }
        } else if (item.nodeType === 'OVERSTATIONPREPARE') {
          let OVERSTATIONPREPARELanguage = ``;
          // let recordFiledsItemStr = '';
          // item.recordFiledsList = this._filter(item.recordFiledsList, (recordItem) => {
          //     return recordItem.field != '';
          // });
          // this._forEach(item.recordFiledsList, (recordFiledsItem) => {
          //     recordFiledsItemStr += `(src:${recordFiledsItem.field},name:${recordFiledsItem.zhCnName})`;
          //     recordFiledsItemStr += 'AND';
          // });

          let overStationTypeStr = '';
          overStationTypeStr += `(type:${item.overStationType})`;
          OVERSTATIONPREPARELanguage += `{{<type:OverStationPrepare,name:${item.nodeCode}>{${overStationTypeStr}}}}`;
          if (OVERSTATIONPREPARELanguage) {
            sLanguageList.push(OVERSTATIONPREPARELanguage);
          }
        } else if (item.nodeType === 'BINDINGPREPARE') {
          let BINDINGLanguage = ``;
          BINDINGLanguage += `{{<type:BindingPrepare,name:${item.nodeCode}>{(type:${item.bindingType})}}}`;
          if (BINDINGLanguage) {
            sLanguageList.push(BINDINGLanguage);
          }
        } else if (item.nodeType === 'UNBINDINGPREPARE') {
          let UNBINDINGLanguage = ``;
          UNBINDINGLanguage += `{{<type:UnBindingPrepare,name:${item.nodeCode}>{(type:${item.unbindingType})}}}`;
          if (UNBINDINGLanguage) {
            sLanguageList.push(UNBINDINGLanguage);
          }
        } else if (item.nodeType === 'PRINT') {
          let PRINTLanguage = ``;
          PRINTLanguage += `{{<type:Print,name:${item.nodeCode}>{(mappingApiId:${item.mappingApiId},mappingApiName:${item.mappingApiName})}}}`;
          if (PRINTLanguage) {
            sLanguageList.push(PRINTLanguage);
          }
        }
      });
      console.log(sLanguageList);
      let mLanguage = sLanguageList.join('==>');
      console.log(mLanguage);

      //查找开始结束节点
      let startNode = this._find(stationFlowJson.nodeDataArray, { key: 'Start' });
      let endNode = this._find(stationFlowJson.nodeDataArray, { key: 'End' });
      //首尾分别插入开始结束节点
      nodeInfoList.unshift(startNode);
      nodeInfoList.push(endNode);
      //将排序之后所有节点赋值在json中
      stationFlowJson.nodeDataArray = nodeInfoList;
      console.log(stationFlowJson);

      let callbackOption = {
        successDo: {},
        failDo: {}
      };

      let paramMap = {
        id: this.apiFlowId,
        name: this.apiInfo.name,
        code: this.apiInfo.code,
        url: this.apiInfo.url,
        // url: '/mes/cloud/v1/module/product/api/apply/command/spec',
        apiType: 'OPERATION',
        httpMethod: 'POST',
        enabled: true,
        validation: false,
        httpHeaders: {},
        paramsJson: JSON.stringify(this.paramsData),
        option: JSON.stringify(callbackOption),
        zhCnContent: this.apiInfo.zhCnContent,
        apiFlowJson: JSON.stringify(stationFlowJson),
        mlanguage: mLanguage
      };
      console.log(paramMap);
      if (this.apiFlowId) {
        this.apiInfo.paramsJson = JSON.stringify(this.paramsData);
        this.apiInfo.apiFlowJson = JSON.stringify(stationFlowJson);
        this.apiInfo.mlanguage = mLanguage;
        addOrUpdateApi(this.apiInfo).then((res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.getModelFlowInfo(this.apiFlowId);
        });
      } else {
        addOrUpdateApi(paramMap).then((res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          let apiFlowId = this._get(res, 'data.data.id', '');
          this.$router.replace({ path: '/product/model-manage/stationflow-design/edit', query: { apiId: apiFlowId } });
        });
      }
      // }
    },

    /**
     * 通过apiID查询api信息
     */
    getModelFlowInfo(apiId) {
      getApiInfo(apiId).then((res) => {
        if (res.data) {
          this.apiInfo = res.data.data;
          this.paramsData = this._get(res, 'data.data.paramsJson', '');
          this.paramsData = this.paramsData ? JSON.parse(this.paramsData) : [];
          this.displayFlow(res.data.data.apiFlowJson);
        } else {
          this.apiInfo = {};
          this.displayFlow(JSON.stringify(this.defaultData));
          this.selectedNodeInfo = {};
        }
      });
    },

    /**
     * 返回API流程配置
     */
    onReturn() {
      this.$router.replace('/product/model-manage/api-flow-config');
    }
  }
};
